/**
 * 
 * @Project le cOeur - Data Virtualization
 * @Date 08.12.2012
 * @Author Aebi Pascal, Kocher Marc
 * @School BFH-TI Biel, Bachelor Thesis
 *
 */

package main.api.http;

import java.util.List;

import main.api.http.MessageHeaderElement;
import main.api.http.MessageHeaderElementParameter;

/**
 * This class represents a specific message header element defined by the HTTP protocol (RFC-2616).
 */
public class ContentType extends MessageHeaderElement implements Comparable<ContentType> {

	private String type;
	private String subType;
	private double qValue = -1;
	
	/**
	 * Creates a content type.
	 * This class represents a specific message header element defined by the HTTP protocol.
	 * 
	 * @param headerElement The message header element string containing a field name, a field value (can be empty) and parameters.
	 */
	public ContentType(String headerElement) {
		super(headerElement);
		super.parse();
		this.parse();
	}

	/**
	 * Creates a content type.
	 * This class represents a specific message header element defined by the HTTP protocol.
	 * 
	 * @param name The field name.
	 * @param value The field value.
	 * @param parameters The parameters.
	 */
	public ContentType(String name, String value, List<MessageHeaderElementParameter> parameters) {
		super(name, value, parameters);
		this.parse();
	}
	
	@Override
	public void parse() {
		String[] types = super.name.split("/");
		this.type = types[0];
		if(types.length == 2){
			this.subType = types[1];
		}
		if(!super.parameters.isEmpty()){
			for (MessageHeaderElementParameter parameter : super.parameters) {
				if(parameter.getName().equalsIgnoreCase("q")){
					this.qValue = Double.parseDouble(parameter.getValue());
					break;
				}
			}
		}
		if(this.qValue == -1){
			this.qValue = 1.0;
		}
	}
	
	@Override
	public int compareTo(ContentType contentType) {
		if(this.qValue < contentType.qValue){
			return 1;
		}
		else if(this.qValue > contentType.qValue){
			return -1;
		}
		else{
			return 0;
		}
	}
	
	/**
	 * Returns the main type of the content type.
	 * 
	 * @return The type.
	 */
	public String getType() {
		return this.type;
	}
	
	/**
	 * Returns the sub type of the content type.
	 * 
	 * @return The sub type.
	 */
	public String getSubType() {
		return this.subType;
	}
	
	/**
	 * Returns the q value of the content type.
	 * 
	 * @return The q value.
	 */
	public double getQValue() {
		return this.qValue;
	}

}

